//
//  PAChartDetailVC.m
//  PilotSeries
//
//  Created by 黄立强 on 16/7/1.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PAChartDetailVC.h"
#import "ContextMenuVC.h"
#import "PAContextMenuVC.h"
#import "MenuCategory.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"
#import "Masonry.h"
//#import "PAWKWebViewCell.h"
#import <MJExtension.h>
#import "PAMenu.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "ChartConfig.h"
#import "PAUpdateConfigDirectionConfigVC.h"
@import WebKit;
@interface PAChartDetailVC ()<UIPopoverPresentationControllerDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (strong, nonatomic) PAContextMenuVC *categoryVc;

@end

@implementation PAChartDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = YES;
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight;
    }
    [self.view addSubview:self.webView];
    self.splitViewController.presentsWithGesture = NO;
//    self.webView.scrollView.scrollEnabled = YES;
    if (self.viewType ==PAViewTypeGraph) {
        
       UIBarButtonItem *updateChartConfig =  [[UIBarButtonItem alloc] initWithTitle:@"config" style:UIBarButtonItemStylePlain target:self action:@selector(updateChartConfig:)];
        
         UIBarButtonItem *menu = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(clickMenu:)];
          self.navigationItem.rightBarButtonItems  = @[menu];
        
    }
  
    // 2.监听通知
    [self setupNotifications];

}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
//    self.title = self.chartConfig
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.webView.superview).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.webView.userInteractionEnabled = YES;
//    self.webView.navigationDelegate = self;
    [self.view layoutIfNeeded];

//    [self.webView.scrollView setContentOffset:CGPointMake(0, 64) animated:YES];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Bridge"];
//    NSString *js2 = @"function sendMsg(msg){ window.webkit.messageHandlers.Bridge.postMessage(msg);}";
//    WKUserScript *script2 = [[WKUserScript alloc] initWithSource:js2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    [self.webView.configuration.userContentController addUserScript:script2];
}
- (void)setupNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(categoryDidChange:) name:LQCategoryDidChangeNotification object:nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWeb:) name:LQUpdateConfigNotification object:nil];
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.splitViewController.presentsWithGesture = YES;
    self.webView.userInteractionEnabled = NO;
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Bridge"];
    
}
#pragma mark - 监听到通知之后,实现的方法
    
- (void)refreshWeb:(NSNotification *)note{
    self.chartConfig = note.userInfo[@"chartConfig"];
    self.title = self.chartConfig.config[CONFIG_KEY_TITLE];
    NSString *js = [NSString stringWithFormat:@"configUpdate(%@)",[self.chartConfig.config jk_JSONString]];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable obj,NSError * _Nullable error) {
        
    }];
//    [self.webView reload];
}
- (void)categoryDidChange:(NSNotification *)note
{
    // 1.获取信息
    PAMenu *category = note.userInfo[LQCategoryDidChangeNotificationCategoryKey];
//    MenuCategory *subCategory = note.userInfo[LQCategoryDidChangeNotificationSubcategoryKey];
    
//    if (!subCategory) {
//        self.navigationItem.rightBarButtonItem.title =category.name;
//    } else {
//        NSString *title;
//        if ([subCategory.name integerValue] >1) {
//            title = [NSString stringWithFormat:@"%@ %@s",subCategory.name,category.name];
//        }else{
//            title = [NSString stringWithFormat:@"%@ %@",subCategory.name,category.name];
//        }
//        //        NSString *title = [NSString stringWithFormat:@"%@, %@",subCategory.name,category.name];
//        self.navigationItem.rightBarButtonItem.title =title;
//
//    }
    
    
    // 3.退出控制器
    [self.categoryVc dismissViewControllerAnimated:YES completion:^{
//        [self clickContxtMenuWithMenu:category subMenu:nil];
        [self clickContextMenu:category];
    }];
    
    // 4.让Items可以交互
    self.navigationItem.rightBarButtonItem.enabled = YES;
//    LOG(@"categoryDidChange")
}

-(void)clickContextMenu:(PAMenu *) menu{
    NSString *js = [NSString stringWithFormat:@"fireMenuEvent('%@')",menu.eventId];
 
    
    //    [self.webView stringByEvaluatingJavaScriptFromString:js];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        
        
    }];
}

-(void)updateChartConfig:(UIBarButtonItem *)buttonItem
{
    
  
}

-(void)clickMenu:(UIBarButtonItem *)buttonItem
{
    NSString *js = [NSString stringWithFormat: @"JSON.parse(JSON.stringify(highCharts.getContextMenu({callbacks:{reload:function(){window.location.reload();},editParameters:function() {sendMsg('editParameters')}}})))"];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        if(error==nil){
            NSMutableArray *arr = [NSMutableArray new];
            for (int i=0;i < [obj count];i ++) {
                NSMutableDictionary *dict = [obj objectAtIndex:i];
                if(dict[@"enabled"] ==nil){
                    dict[@"enabled"] = @1;
                }
                if(dict[@"type"] != nil && [dict[@"type"] isEqualToString:@"separator"]){
                    
                }else{
                    NSMutableArray *subArr = dict[@"submenu"];
                    
                    [subArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                         NSMutableDictionary *sdict = [subArr objectAtIndex:idx];
                        if(sdict[@"enabled"] ==nil){
                            sdict[@"enabled"] = @1;
                        }
                        if(sdict[@"type"] != nil && [sdict[@"type"] isEqualToString:@"separator"]){
                            [subArr removeObjectAtIndex:idx];
                        }
                        NSMutableArray *ssubArr = sdict[@"submenu"];
                        [ssubArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idxx, BOOL * _Nonnull stop) {
                            NSMutableDictionary *ssdict = [ssubArr objectAtIndex:idxx];
                            if(ssdict[@"enabled"] ==nil){
                                ssdict[@"enabled"] = @1;
                            }
                            if(ssdict[@"type"] != nil && [ssdict[@"type"] isEqualToString:@"separator"]){
                                [ssubArr removeObjectAtIndex:idxx];
                            }
                        }];
                    }];
//                    for (int idx=0;idx < [subArr count];idx ++){
//                        NSMutableDictionary *sdict = [subArr objectAtIndex:idx];
//                        if(sdict[@"enabled"] ==nil){
//                            sdict[@"enabled"] = @1;
//                        }
//                        NSMutableArray *ssubArr = sdict[@"submenu"];
//                        for (int idxx=0;idxx < [ssubArr count];idxx ++) {
//                            NSMutableDictionary *ssdict = [ssubArr objectAtIndex:idxx];
//                            if(ssdict[@"enabled"] ==nil){
//                                ssdict[@"enabled"] = @1;
//                            }
//                            if(ssdict[@"type"] != nil && [ssdict[@"type"] isEqualToString:@"separator"]){
//                                [ssubArr removeObjectAtIndex:idxx];
//                            }
//                        }
//                        if(sdict[@"type"] != nil && [sdict[@"type"] isEqualToString:@"separator"]){
//                            [subArr removeObjectAtIndex:idx];
//                        }
//
//                    }
                    PAMenu *menu = [PAMenu mj_objectWithKeyValues:dict];
                    [arr addObject:menu];
                }
            }
            // 1.创建控制器
            PAContextMenuVC *categoryVc = [[PAContextMenuVC alloc] init];
            
            // 2.设置弹出样式
            categoryVc.modalPresentationStyle = UIModalPresentationPopover;
            categoryVc.preferredContentSize = CGSizeMake(categoryVc.view.bounds.size.width/2,categoryVc.view.bounds.size.height-200);
            
            // 3.设置当前控制器成为popoverController的代理
            categoryVc.popoverPresentationController.delegate = self;
            
            [categoryVc setCategories:arr];
            categoryVc.popoverPresentationController.barButtonItem = buttonItem;
            
            self.categoryVc = categoryVc;
            [self presentViewController:categoryVc animated:YES completion:^{
                
            }];
        }
        
    }];
    
}

//- (ContextMenuVC *)categoryVc
//{
//    if (_categoryVc == nil) {
//        // 1.创建控制器
//        _categoryVc = [[ContextMenuVC alloc] init];
//
//        // 2.设置弹出样式
//        _categoryVc.modalPresentationStyle = UIModalPresentationPopover;
//
//        // 3.设置当前控制器成为popoverController的代理
//        _categoryVc.popoverPresentationController.delegate = self;
//    }
//    return _categoryVc;
//}


//- (PAContextMenuVC *)categoryVc
//{
//    if (_categoryVc == nil) {
//        // 1.创建控制器
//        _categoryVc = [[PAContextMenuVC alloc] init];
//
//        // 2.设置弹出样式
//        _categoryVc.modalPresentationStyle = UIModalPresentationPopover;
//        _categoryVc.preferredContentSize = _categoryVc.view.bounds.size;
//
//        // 3.设置当前控制器成为popoverController的代理
//        _categoryVc.popoverPresentationController.delegate = self;
//    }
//    return _categoryVc;
//}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    LOGMETHOD
}
- (void)popoverPresentationControllerDidDismissPopover:(UIPopoverPresentationController *)popoverPresentationController
{
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

- (void)clickContxtMenuWithMenu:( MenuCategory *)category subMenu:(MenuCategory *)subCategory{
    if (category==nil) {
        return;
    }
  
    NSString *js;
    if (subCategory!=nil) {
        js = [NSString stringWithFormat:@"clickContxtMenuWithsubMenu('%@','%@');",category.type,subCategory.type];
    }else{
        js = [NSString stringWithFormat:@"clickContxtMenuWithMenu('%@');",category.type];
    }
    
//    [self.webView stringByEvaluatingJavaScriptFromString:js];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
        
        
    }];
}
    
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
//    [webView.configuration.userContentController addScriptMessageHandler:self name:@"Bridge"];
//    NSString *js2 = @"function sendMsg(msg){ window.webkit.messageHandlers.Bridge.postMessage(msg);}";
//    WKUserScript *script2 = [[WKUserScript alloc] initWithSource:js2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    [webView.configuration.userContentController addUserScript:script2];
}


-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if([message.name isEqualToString:@"Bridge"]){
//         NSLog(@"扫一扫message%@",message.body);
        if([message.body isEqualToString:@"editParameters"]){
            [self editParameters];
        }
    }
}
- (void) setChartConfig:(ChartConfig *)chartConfig{
    _chartConfig = chartConfig;
    self.title = chartConfig.config[CONFIG_KEY_TITLE];
}
    
- (void) editParameters {
    NSDictionary *dic =  self.chartConfig.config[@"parameters"];
    if (dic[@"directionname"] == nil) {
        // do not support
        return;
    }
    PAUpdateConfigDirectionConfigVC *vc = [PAUpdateConfigDirectionConfigVC new];
    vc.chartConfig = self.chartConfig;
    // 2.设置弹出样式
    vc.modalPresentationStyle = UIModalPresentationPopover;
//    vc.preferredContentSize = CGSizeMake(vc.view.bounds.size.width-200,vc.view.bounds.size.height-200);
    
    // 3.设置当前控制器成为popoverController的代理
    vc.popoverPresentationController.delegate = self;
    vc.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems[0];
//    vc.popoverPresentationController.barButtonItem = buttonItem;
   
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    
}
@end
